import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * 学生成绩管理系统图形界面
 */
public class GradeManagementSystemGUI extends JFrame {
    private GradeManager gradeManager;
    private JTable gradeTable;
    private DefaultTableModel tableModel;
    private TotalScoreCalculator totalScoreCalculator;
    private CourseAverageScoreCalculator courseAverageScoreCalculator;

    public GradeManagementSystemGUI() {
        gradeManager = new GradeManager();
        totalScoreCalculator = new TotalScoreCalculatorImpl();
        courseAverageScoreCalculator = new CourseAverageScoreCalculatorImpl();
        initComponents();
    }

    private void initComponents() {
        setTitle("学生成绩管理系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        tableModel = new DefaultTableModel(
                new String[]{"学号", "姓名", "课程名称", "分数"}, 0
        );
        gradeTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(gradeTable);

        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("添加成绩");
        JButton refreshButton = new JButton("刷新表格");
        JButton deleteButton = new JButton("删除选中成绩");
        JButton totalScoreButton = new JButton("计算个人总成绩");
        JButton averageScoreButton = new JButton("计算课程平均分");

        buttonPanel.add(addButton);
        buttonPanel.add(refreshButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(totalScoreButton);
        buttonPanel.add(averageScoreButton);

        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        refreshTable();

        addButton.addActionListener(e -> showAddGradeDialog());
        refreshButton.addActionListener(e -> refreshTable());
        deleteButton.addActionListener(e -> deleteSelectedGrade());
        totalScoreButton.addActionListener(e -> calculateTotalScore());
        averageScoreButton.addActionListener(e -> calculateCourseAverageScore());
    }

    private void refreshTable() {
        tableModel.setRowCount(0);
        List<Grade> grades = gradeManager.getAllGrades();
        for (Grade grade : grades) {
            tableModel.addRow(new Object[]{
                    grade.getStudent().getStudentId(),
                    grade.getStudent().getName(),
                    grade.getCourse().getCourseName(),
                    grade.getScore()
            });
        }
    }

    private void showAddGradeDialog() {
        JDialog dialog = new JDialog(this, "添加成绩", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new GridLayout(5, 2));

        JTextField studentIdField = new JTextField();
        JTextField nameField = new JTextField();
        JTextField courseNameField = new JTextField();
        JTextField scoreField = new JTextField();
        JButton saveButton = new JButton("保存");

        dialog.add(new JLabel("学号:"));
        dialog.add(studentIdField);
        dialog.add(new JLabel("姓名:"));
        dialog.add(nameField);
        dialog.add(new JLabel("课程名称:"));
        dialog.add(courseNameField);
        dialog.add(new JLabel("成绩:"));
        dialog.add(scoreField);
        dialog.add(new JLabel());
        dialog.add(saveButton);

        saveButton.addActionListener(e -> {
            try {
                String studentId = studentIdField.getText();
                String name = nameField.getText();
                String courseName = courseNameField.getText();
                double score = Double.parseDouble(scoreField.getText());

                Student student = new Student(studentId, name);
                Course course = new Course(courseName);
                Grade grade = new Grade(student, course, score);

                gradeManager.addGrade(grade);
                refreshTable();
                dialog.dispose();
                JOptionPane.showMessageDialog(null, "成绩添加成功!");
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "请输入有效的成绩!");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "添加失败: " + ex.getMessage());
            }
        });

        dialog.setVisible(true);
    }

    private void deleteSelectedGrade() {
        int selectedRow = gradeTable.getSelectedRow();
        if (selectedRow != -1) {
            String studentId = (String) tableModel.getValueAt(selectedRow, 0);
            String courseName = (String) tableModel.getValueAt(selectedRow, 2);
            List<Grade> grades = gradeManager.getAllGrades();
            for (Grade grade : grades) {
                if (grade.getStudent().getStudentId().equals(studentId) &&
                        grade.getCourse().getCourseName().equals(courseName)) {
                    grades.remove(grade);
                    DataPersistence.saveGrades(grades);
                    refreshTable();
                    JOptionPane.showMessageDialog(null, "成绩删除成功!");
                    return;
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "请选择要删除的成绩记录!");
        }
    }

    private void calculateTotalScore() {
        String input = JOptionPane.showInputDialog("请输入要计算总成绩的学生学号或姓名:");
        if (input != null && !input.isEmpty()) {
            List<Grade> grades = gradeManager.getAllGrades();
            double totalScore = totalScoreCalculator.calculateTotalScore(grades, input);
            if (totalScore > 0) {
                String studentInfo = getStudentInfo(grades, input);
                JOptionPane.showMessageDialog(null,
                        studentInfo + " 的总成绩为: " + totalScore);
            } else {
                JOptionPane.showMessageDialog(null, "未找到该学生的成绩记录!");
            }
        }
    }

    private String getStudentInfo(List<Grade> grades, String input) {
        for (Grade grade : grades) {
            Student student = grade.getStudent();
            if (student.getStudentId().equals(input) || student.getName().equals(input)) {
                return "学号: " + student.getStudentId() + ", 姓名: " + student.getName();
            }
        }
        return "";
    }

    private void calculateCourseAverageScore() {
        String courseName = JOptionPane.showInputDialog("请输入要计算平均分的课程名称:");
        if (courseName != null && !courseName.isEmpty()) {
            List<Grade> grades = gradeManager.getAllGrades();
            double averageScore = courseAverageScoreCalculator.calculateCourseAverageScore(grades, courseName);
            if (averageScore > 0) {
                JOptionPane.showMessageDialog(null,
                        courseName + " 课程的平均分为: " + averageScore);
            } else {
                JOptionPane.showMessageDialog(null, "未找到该课程的成绩记录!");
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new GradeManagementSystemGUI().setVisible(true));
    }
}    